import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';
import router from '../router';

export const baseURL = '/api';
// export const baseURL = 'http://192.168.76.233:8888';
// export const baseURL = 'http://localhost:8888';
// export const baseURL = 'http://ycy.free.svipss.top';  //线上地址
// export const baseURL = 'http://47.108.93.89:8888';  //线上地址

const service = axios.create({
  baseURL: baseURL,
  timeout: 50000,
  headers: {
    'Content-Type': 'application/json;charset=utf-8',
  },
});

//请求拦截
service.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token');

    // if (!config.headers) config.headers = {};

    if (token) config.headers.token = token;
    return config;
  },
  err => {
    return Promise.reject(err);
  }
);

//响应拦截
service.interceptors.response.use(
  res => {
    // const code = res.status;
    const code = res.data.code
    if (code === 200) return Promise.resolve(res.data);
    else if(code == 403) {
      //token过期
      ElMessageBox.confirm(
        '为保证账号安全,系统最大登录时长为6小时,现已达到。',
        '请重新登录',
        {
          confirmButtonText: '确 定',
          showCancelButton: false,
          showClose: false,
          type: 'error',
          center: true,
        }
      ).then(() => { router.replace('/login') });
      return Promise.resolve(res.data);
    }
    else {
      ElMessage.error(res.data.message);
      return Promise.resolve(res.data);
    }
  },err => {
    // if(code == 403) 
    if(err.response.data.code == 403) ElMessage.error('缺失请求权限');
    else ElMessage.error('服务器错误');
    return Promise.reject(err.response);
  }
);

export default service;
